<?php

class Application_Model_BlogMapper extends Application_Model_AbstractMapper {

	protected $_dbTableName = "blog"; //used in abstract mapper for Zend_Db_Table_Abstract

	/**
	 * @param  Zend_Db_Table_Row_Abstract $row
	 * @return Application_Model_Blog
	 */
	protected function _convertToModel($row) {
		$model = new Application_Model_Blog();
		//$model->setId($row->id)->setUserId($row->userId)->setTitle($row->title)->setPosting($row->posting)->setCreated($row->created);
		$model->setId($row['id'])->setUserId($row['userId'])->setTitle($row['title'])->setPosting($row['posting'])->setCreated($row['created']);
		return $model;
	}

	/**
	 * key eq null -> insert, sonst update
	 * @param Application_Model_Blog $blog
	 */
	public function save(Application_Model_Blog $blog) {
		$data = array('id' => $blog->getId(), 'userId' => $blog->getUserid(), 'title' => $blog->getTitle(), 'posting' => $blog->getposting(),
			'created' => date('Y-m-d H:i:s'),);

		if (null === ($id = $blog->getId())) {
			unset($data['id']);
			$this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
		$this->_invalidateCache("$id");
	}

	/**
	 * sucht auf DB-Primary index
	 * @param int $id
	 * @return Application_Model_Blog
	 * @throws Exception
	 */

	public function find($id) {

		if (!ctype_digit((string)$id)) {
			throw new Exception('Applikationsfehler - DB-Key User nicht Integer');
		}
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			throw new Exception('Applikationsfehler - DB-Key Blog nicht verhanden');
		}
		$blog = $this->_convertToModel($result->current());
		return $blog;
	}

	/**
	 * gibt rowset zurück
	 * @param string $userId
	 * @return Application_Model_Blog[]
	 */
	public function fetchAll($userId) {
		$select = $this->getDbTable()->select()->where('userId = ?', $userId)->order('userId ASC', 10, 0);
		$resultSet = $this->getDbTable()->fetchAll($select);
		return $this->_convertToModelArray($resultSet);
	}

	/**
	 * returns exactly one row
	 * @param int $userId
	 * @return Application_Model_Blog
	 * @throws Exception
	 */
	public function fetchRow($userId) {
		$select = $this->getDbTable()->select()->where('userId = ?', $userId);
		$resultSet[] = $this->getDbTable()->fetchRow($select);
		if (count($resultSet) > 1) {
			throw new Exception('Applikationsfehler - fetchrow bringt mehr als 1 Rec zurück');
		}

		$blog = $this->_convertToModel($resultSet[0]);
		return $blog;
	}

	/**
	 * @param int $id
	 */
	public function deleteRow($id) {
		$where = $this->getDbTable()->getAdapter()->quoteInto('id = ?', $id);
		$this->getDbTable()->delete($where);
		$this->_invalidateCache("$id");
	}
}
